package com.aos.erp.fs.show.view;

import com.aos.erp.fs.enums.FileUriType;
import com.aos.erp.fs.model.SysFile;
import com.aos.erp.fs.show.FileView;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@Slf4j
@Component
@RefreshScope
public class LocalFileView implements FileView {


    @Value("${uploadFolder:/}")
    private String uploadFolder = "";

    @Override
    public FileUriType getUriType() {
        return FileUriType.local;
    }

    @Override
    public void render(HttpServletRequest request, HttpServletResponse response, SysFile sysFile) {
        //下载文件
        File file = new File(uploadFolder + sysFile.getUriSrc());
        try {
            FileInputStream fis = new FileInputStream(file);
            IOUtils.copy(fis, response.getOutputStream(), 1024);
            IOUtils.closeQuietly(fis, response.getOutputStream());
        } catch (FileNotFoundException e) {
            this.fileNotFound(request, response);
        } catch (IOException e) {
            log.error(sysFile.toString());
            log.error(e.getMessage(), e);
        }
    }

}
